/**
 * 时间提醒
 * @see Ticket #36
 * @author Rox <rox@taomee.com>
 *
 * 行为：
 * 	1) 页面初始化：读取用户最近登录的时间戳（cookie || /user/getOnlineTime）
 *  2) 定时更新时间，检查当前时间和登录时间戳，发现 >= 1h，则：
 *  	弹出提醒，重置时间戳
 */
(function($) {
    if ( $('iframe').length > 0 ) return;
    if ( window.no_reminder ) return;

    var reminder = (function() {
        var REMINDER_INTERVAL = 3600;   // 提醒间隔，单位：秒

        var OFFSET_TOP  = 100;          // 弹出框到顶部距离，单位：px
        var OFFSET_LEFT = 181;          // 弹出框宽度/2

        var reminder_mask      = $('<div></div>')
                                    .css('position', 'absolute')
                                    .css('top', 0)
                                    .css('left', 0)
                                    .css('z-index', 11)
                                    .css('width', '100%')
                                    .css('height', '100%')
                                    .css('background-color', '#333')
                                    .css('opacity', 0.8)
                                    .hide()
                                    .css('width', 1440)
                                    .css('height', 1179)
                                    .appendTo(document.body);

        var reminder_container = $('<div></div>')
                                    .css('position', 'absolute')
                                    .css('z-index', 12)
                                    .css('left', '50%');

        var padLeft = function(str, length, pad_char) {
            str = str.toString();
            if ( str.length >= length ) return str;

            var offset = length - str.length;
            var pad_str = '';
            for(var i=0; i<offset; ++i)
            {
                pad_str += pad_char;
            }

            return pad_str + str;
        };

        var readCookie = function (key) {
            var value = document.cookie.match('(?:^|;)\\s*' + key + '=([^;]*)');
            return (value) ? decodeURIComponent(value[1]) : null;
        };

        var setOnlineTime = function(timestr) {
            var expires = new Date();
            expires.setTime(expires.getTime() + 3600000 * 1.5);
            document.cookie = 'online_since=' + encodeURIComponent(timestr) + ';expires=' + expires.toGMTString() + ';path=/;domain=.da.61.com';
        };

        var clearOnlineTime = function() {
            var expires = new Date();
            expires.setTime(expires.getTime() - 36000);
            document.cookie = 'online_since=;expires=' + expires.toGMTString() + ';path=/;domain=.da.61.com';
            document.cookie = 'online_since=;expires=' + expires.toGMTString() + ';path=/';
            document.cookie = 'online_since=;expires=' + expires.toGMTString() + ';path=/;domain=test.da.61.com';
        };

        var hideSWFs = function() {
            try {
                $.hide_image_switcher();
                hideGame();
            } catch(ex) {}
        };
        var showSWFS = function() {
            try {
                $.resume_image_switcher();
                showGame();
            } catch(ex) {}
        };

        var hideReminder = function() {
            reminder_container.fadeOut();
            reminder_mask.hide();
            showSWFS();
        };

        var showReminder = function() {
            reminder_container.empty()
                              .load('/user/getReminder', function(data) {
                                  hideSWFs();

                                  var now = new Date();
                                  clearOnlineTime();
                                  setOnlineTime(now.toString());
                                  reminder_mask.css('width', $('body').width())
                                               .css('height', $('body').height())
                                               .show();
                                  reminder_container.appendTo(document.body)
                                                     .css('top', OFFSET_TOP + $(document).scrollTop())
                                                     .css('margin-left', -OFFSET_LEFT)
                                                     .fadeIn('fast');
                                  $('.btnoff', reminder_container).click(function (e) {
                                      e.preventDefault();
                                      hideReminder();
                                  });
                              });
        };

        var updateTime = function() {
            var ct = window.setInterval(function() {
                var now = new Date();
                var hh  = padLeft(now.getHours(), 2, '0');
                var mm  = padLeft(now.getMinutes(), 2, '0');
                $('.top_clock .time').html(hh + ':' + mm);
            }, 1000);
        };

        var checkTime = function(online_since) {
            var now = new Date();
            var then = new Date(online_since);
            var ts_offset = now - then;
            if ( ts_offset >= REMINDER_INTERVAL*1000 )
            {
                clearOnlineTime();
                setOnlineTime(now.toString());
                if ( ts_offset <= REMINDER_INTERVAL*1000 + 900*1000 ) // 1h + 15m
                {
                    showReminder();
                }
            }
        };

        return {
            init: function() {
                // 时钟
                //updateTime(); // is not needed coz clock is integrated into top SWF

                // 读取上次登录时间
                var online_since = readCookie('online_since');
                if ( !online_since )
                {
                    var now = new Date();
                    online_since = now.toString();
                }
                setOnlineTime(online_since);

                // 检查时间是否到 1h
                checkTime(online_since);

                // debug
                //$('div.new_red').click(function(e) {
                //    e.preventDefault();
                //    showReminder();
                //});
            }
        };
    })();

    reminder.init();
})(jQuery);
